import editForm from "../form.vue";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, toRaw, h, onUnmounted } from "vue";
import {
  getAgentOptionList,
  getAgentServerStatus,
  restartAgentServer
} from "@/api/agent";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import { agentOptionsType } from "@/utils/commonType";
import { ElMessageBox } from "element-plus";

export function useAgentOptions(tableRef: Ref) {
  const form = reactive({
    section: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const appStatus = ref("服务  停止");
  const timerId = ref();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 60
    },
    {
      label: "所属配置块",
      prop: "sectionName",
      minWidth: 100
    },
    {
      label: "配置项",
      prop: "optionItem",
      minWidth: 140
    },
    {
      label: "配置项说明",
      prop: "optionDesc"
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  async function onSearch() {
    loading.value = true;
    getAgentOptionList(form.section)
      .then(result => {
        dataList.value = result.data.list;
        pagination.total = result.data.total;
        pagination.pageSize = result.data.pageSize;
        pagination.currentPage = result.data.currentPage;
        pagination.pageCount = result.data.totalPage;
      })
      .catch(err => {
        message(`获取配置清单失败：${err.message}`, {
          type: "error"
        });
      });

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function restartAgent() {
    ElMessageBox.confirm(`确认要重启代理服务吗?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    })
      .then(async () => {
        restartAgentServer()
          .then(result => {
            if (result.data) {
              message(`正在重启代理服务`, {
                type: "success"
              });
            } else {
              message(`重启代理服务失败：${result.message}`, {
                type: "error"
              });
            }
          })
          .catch(err => {
            message(`重启代理服务失败：${err.message}`, {
              type: "error"
            });
          });
        appStatus.value = "服务  停止";
      })
      .catch(() => {});
  }
  const formRef = ref();

  function openDialog(title = "新增", row?: agentOptionsType) {
    addDialog({
      title: `${title}账户`,
      props: {
        formInline: {
          pid: row?.pid ?? "",
          section: row?.section ?? "",
          optionItem: row?.optionItem ?? "",
          optionDesc: row?.optionDesc ?? "",
          editStatus: title == "新增" ? false : true
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: false,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as agentOptionsType;
        function chores() {
          message(`您${title}了账户名称为${curData.optionItem}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // addAccount(curData)
              //   .then(function (data) {
              //     chores();
              //     onSearch(); // 刷新表格数据
              //   })
              //   .catch(function (err) {
              //     message(`${title}账户失败:${err.message}`, {
              //       type: "error"
              //     });
              //   });
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              // updateAccount(curData)
              //   .then(function (data) {
              //     chores();
              //     onRefash();
              //   })
              //   .catch(function (err) {
              //     message(`${title}账户失败:${err.message}`, {
              //       type: "error"
              //     });
              //   });
            }
          }
        });
      }
    });
  }

  onMounted(() => {
    onSearch();
    getAgentServerStatus()
      .then(result => {
        if (result.data) {
          appStatus.value = "服务运行中";
        } else {
          appStatus.value = "服务  停止";
        }
      })
      .catch(err => {
        appStatus.value = "服务  停止";
      });
    timerId.value = setInterval(() => {
      // 接口
      // appStatus.value
      getAgentServerStatus()
        .then(result => {
          if (result.data) {
            appStatus.value = "服务运行中";
          } else {
            appStatus.value = "服务  停止";
          }
        })
        .catch(err => {
          appStatus.value = "服务  停止";
        });
    }, 5000);
  });

  onUnmounted(() => {
    if (timerId.value) {
      clearInterval(timerId.value);
    }
  });
  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    appStatus,
    onSearch,
    restartAgent,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
